package com.zgs.mall.cart.interceptor;

import com.zgs.common.constant.CartConstant;
import com.zgs.mall.cart.vo.MemberRespVo;
import com.zgs.mall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 拦截器
 */
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> local =new ThreadLocal();
    //Controller方法处理之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo infoTo =new UserInfoTo();
        //判断是否登录
        HttpSession session = request.getSession();
        MemberRespVo memberRespVo=  (MemberRespVo)session.getAttribute("user_data");
        if(memberRespVo !=null){//登录了
            infoTo.setUserId(memberRespVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies !=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_COOKIE_NAME)){
                    infoTo.setUserKey(cookie.getValue());
                    infoTo.setUs(true);
                }
            }
        }
        if(StringUtils.isEmpty(infoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            infoTo.setUserKey(uuid);
        }
        local.set(infoTo);
        return true;
    }

    /**
     * 调用前提：preHandle返回true
     * 调用时间：Controller方法处理完之后，DispatcherServlet进行视图的渲染之前，也就是说在这个方法中你可以对ModelAndView进行操作
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo infoTo = local.get();
        Boolean us = infoTo.getUs();
        if (!us){
            Cookie cookie = new Cookie("user-key", infoTo.getUserKey());
            cookie.setDomain(".gulimall.com");
            response.addCookie(cookie);
        }
    }
}
